﻿using System;
using Contacts.Data;
using DevExpress.Utils;
using Contacts.Controls;
using DevExpress.XtraTab;
using DevExpress.XtraBars;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTab.ViewInfo;
using DevExpress.XtraReports.UserDesigner;
using Contacts.Reports;
using DevExpress.XtraReports.UI;
using System.IO;
using MetadataProcessor;

namespace Contacts
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            MetadataController.GenerateAssembly();
            HomeTab();
            LoadReportMenu();
        }

        private IControl GetControl(XtraTabPage page)
        {
            if (page != null && page.Controls.Count > 0 && page.Controls[0] is IControl)
                return (IControl)page.Controls[0];
            return null;
        }

        private XtraTabPage Home { get; set; }

        #region Logic
        private void HomeTab()
        {
            if (Home != null)
                tabMain.SelectedTabPage = Home;
        }

        private void RefreshCurrent()
        {
            IControl control = GetControl(tabMain.SelectedTabPage);
            if (control != null)
            {
                control.Reload();
            }
        }

        private void CloseTab(TabType type, int id = -1)
        {
            foreach (XtraTabPage t in tabMain.TabPages)
            {
                IControl control = GetControl(t);
                if (control != null
                    && control.TabType == type
                    && control.Id == id)
                {

                    if (control.IsDirty &&
                        XtraMessageBox.Show("The current item has been changed. Save Changes?", "Save Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        control.Save();

                    t.PageVisible = false;
                    t.Dispose();
                    break;

                }
            }
        }
        #endregion

        #region Events

        private void barHome_ItemClick(object sender, ItemClickEventArgs e)
        {
            HomeTab();
        }

        private void tabMain_CloseButtonClick(object sender, EventArgs e)
        {
            ClosePageButtonEventArgs args = (ClosePageButtonEventArgs)e;
            tabMain.SelectedTabPage = (XtraTabPage)args.Page;
            IControl control = GetControl(tabMain.SelectedTabPage);
            CloseTab(control.TabType, control.Id);
        }

        private void barRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshCurrent();
        }

        private void barClose_ItemClick(object sender, ItemClickEventArgs e)
        {
            Application.Exit();
        }

        private void menuHome_ItemClick(object sender, ItemClickEventArgs e)
        {
            HomeTab();
        }



        private void menuRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            RefreshCurrent();
        }


        #endregion

        private void LoadDesigner(ReportType type)
        {
            //XRDesignForm form = new XRDesignForm();
            //var controller = form.DesignMdiController;
            //if (type == ReportType.Category)
            //    controller.AddService(typeof(ReportTypeService),
            //        new CategoryReportService());
            //else
            //    //controller.AddService(typeof(ReportTypeService),
            //    //    new PersonReportService());
            //    controller.AddService(typeof(ReportTypeService),
            //        new UnknownReportService());

            //controller.CreateNewReport();
            //form.DesignDockManager[DesignDockPanelType.FieldList].Show();
            //form.ShowDialog();
            //LoadReportMenu();
        }

        private void LoadDesigner(ReportTemplateMetadata metadata)
        {
            XRDesignForm form = new XRDesignForm();
            var controller = form.DesignMdiController;

            controller.AddService(typeof(ReportTypeService),
                new GenericReportService(metadata));
            controller.CreateNewReport();
            form.DesignDockManager[DesignDockPanelType.FieldList].Show();
            form.ShowDialog();
            LoadReportMenu();
        }

        //private void LoadDesigner(string url)
        //{
        //    //var report = XtraReport.FromFile(url, true);
        //    //if (report is IReport)
        //    //    (report as IReport).LoadDataSource();
        //    //report.ShowDesignerDialog();

        //    //EditorControl preview = new EditorControl(url);
        //    //preview.Reload();
        //    //preview.Dock = DockStyle.Fill;
        //    //var tab = tabMain.TabPages.Add();
        //    //tab.Text = "Edit";
        //    //tab.Controls.Add(preview);

        //    //tabMain.SelectedTabPage = tab;
        //}

        private void LoadPreview(string url)
        {
            //var report = XtraReport.FromFile(url, true);
            //if (report is IReport)
            //    (report as IReport).LoadDataSource();
            //report.ShowPreview();

            PreviewControl preview = new PreviewControl(url);
            preview.Reload();
            preview.Dock = DockStyle.Fill;
            var tab = tabMain.TabPages.Add();
            tab.Text = "Preview";
            tab.Controls.Add(preview);

            tabMain.SelectedTabPage = tab;


        }

        private void LoadReportMenu()
        {
            barReportPreview.ClearLinks();
            var path = Application
                .ExecutablePath
                .Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
            foreach (var f in Directory.EnumerateFiles(path, "*.repx"))
            {
                BarSubItem b = new BarSubItem(barMain, f);
                BarButtonItem edit = new BarButtonItem(barMain, "Edit");
                edit.ItemClick += new ItemClickEventHandler(edit_ItemClick);
                edit.Tag = f;
                b.AddItem(edit);
                b.Tag = f;
                b.Caption = f.Substring(f.LastIndexOf('\\') + 1, f.Length - f.LastIndexOf('\\') - 1);
                b.ItemClick += new ItemClickEventHandler(preview_ItemClick);
                barReportPreview.ItemLinks.Add(b);
            }

            var reportMenus = MetadataController.GetEntities();

            //  this.barCreateReport.LinksPersistInfo.Clear();
            foreach (var reportMenu in reportMenus)
            {
                var barButtonItem = new BarButtonItem();
                barButtonItem.Caption = reportMenu;
                barButtonItem.Name = "barBy" + reportMenu;
                barButtonItem.ItemClick += new ItemClickEventHandler(report_ItemClick);
                barButtonItem.Tag = reportMenu;
                this.barMain.Items.Add(barButtonItem);

                this.barCreateReport.LinksPersistInfo.Add(new LinkPersistInfo(barButtonItem));
            }
        }

        void report_ItemClick(object sender, ItemClickEventArgs e)
        {
            var tag = e.Item.Tag;
            LoadDesigner(new ReportTemplateMetadata()
                {
                    EntityName = string.Format("ReportDTO.{0}", tag),
                    ReturnType = string.Format("ReportDTO.{0}", tag),
                    Query = string.Format(@"context.{0}s.ToList<object>();", tag)
                });
        }

        void preview_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadPreview(e.Item.Tag.ToString());
        }

        void edit_ItemClick(object sender, ItemClickEventArgs e)
        {
           // LoadDesigner(e.Item.Tag.ToString());
        }

        private void barByPerson_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadDesigner(ReportType.Person);
        }

        private void barByCategory_ItemClick(object sender, ItemClickEventArgs e)
        {
            LoadDesigner(ReportType.Category);
        }
    }
}
